package com.momei.security.handler;

import com.alibaba.fastjson.JSON;
import com.momei.security.MyUserDetails;
import com.momei.util.JwtTokenUtil;
import com.momei.util.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 *@description: 登录成功
 *@author: momo
 *@time: 2020/9/11
 */
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(MyAuthenticationSuccessHandler.class);

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException {
        LOGGER.info("登陆成功!");
        // 取得账号信息
        MyUserDetails userDetails = (MyUserDetails) authentication.getPrincipal();
        SecurityContextHolder.getContext().setAuthentication(authentication);

        String token = redisUtils.getTokenFromRedis(userDetails.getUsername());

        JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
        if(!StringUtils.isNotBlank(token)) {
            token = jwtTokenUtil.generateToken(userDetails);
            // 把新的token存储到缓存中
            redisUtils.setToken2Redis(userDetails.getUsername(), token);
        }else{
            token = jwtTokenUtil.refreshToken(token);
            redisUtils.reSetToken2Redis(userDetails.getUsername(),  token);
        }

        Map<String,Object> data = new HashMap<>();
        data.put("token", token);
        data.put("success", "true");
        data.put("errorCode", 200);
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(data));
    }
}
